home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / gmp-132.lha / gmp-1.3.2 / mpz_random2.c < prev    next >
C/C++ Source or Header  |  1993-05-02  |  2KB  |  89 lines

  1. /* mpz_random2 -- Generate a positive random MP_INT of specified size, with
  2.    long runs of consecutive ones and zeros in the binary representation.
  3.    Meant for testing of other MP routines.
  4.  
  5. Copyright (C) 1991, 1993 Free Software Foundation, Inc.
  6.  
  7. This file is part of the GNU MP Library.
  8.  
  9. The GNU MP Library is free software; you can redistribute it and/or modify
  10. it under the terms of the GNU General Public License as published by
  11. the Free Software Foundation; either version 2, or (at your option)
  12. any later version.
  13.  
  14. The GNU MP Library is distributed in the hope that it will be useful,
  15. but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. GNU General Public License for more details.
  18.  
  19. You should have received a copy of the GNU General Public License
  20. along with the GNU MP Library; see the file COPYING.  If not, write to
  21. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  22.  
  23. #include "gmp.h"
  24. #include "gmp-impl.h"
  25.  
  26. #if defined (hpux) || defined (__alpha__)
  27. /* HPUX lacks random().  DEC Alpha's random() returns a double.  */
  28. static inline long
  29. random ()
  30. {
  31.   return mrand48 ();
  32. }
  33. #else
  34. long random ();
  35. #endif
  36.  
  37. void
  38. #ifdef __STDC__
  39. mpz_random2 (MP_INT *x, mp_size size)
  40. #else
  41. mpz_random2 (x, size)
  42.      MP_INT *x;
  43.      mp_size size;
  44. #endif
  45. {
  46.   mp_limb ran, cy_limb;
  47.   mp_ptr xp;
  48.   mp_size xsize, abs_size;
  49.   int n_bits;
  50.  
  51.   abs_size = ABS (size);
  52.  
  53.   if (abs_size != 0)
  54.     {
  55.       if (x->alloc < abs_size)
  56.     _mpz_realloc (x, abs_size);
  57.       xp = x->d;
  58.  
  59.       xp[0] = 1;
  60.       for (xsize = 1;; )
  61.     {
  62.       ran = random ();
  63.       n_bits = (ran >> 1) % BITS_PER_MP_LIMB;
  64.  
  65.       if (n_bits == 0)
  66.         {
  67.           if (xsize == abs_size)
  68.         break;
  69.         }
  70.       else
  71.         {
  72.           /* Would we get a too large result in mpn_lshift?  */
  73.           if (xsize == abs_size
  74.           && (xp[xsize - 1] >> (BITS_PER_MP_LIMB - n_bits)) != 0)
  75.         break;
  76.  
  77.           cy_limb = mpn_lshift (xp, xp, xsize, n_bits);
  78.           if (cy_limb != 0)
  79.         xp[xsize++] = cy_limb;
  80.  
  81.           if (ran & 1)
  82.         xp[0] |= ((mp_limb) 1 << n_bits) - 1;
  83.         }
  84.     }
  85.     }
  86.  
  87.   x->size = size;
  88. }
  89.